<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { areaList } from '@vant/area-data'
import {
  addAddressService,
  updateAddressService,
  getAddressDetailService,
  deleteAddressService,
} from '@/api/medicine'
import { Dialog, Toast } from 'vant'
const props = defineProps<{
  show: boolean
  id?: string
}>()
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'refresh'): void
}>()
const onClose = () => {
  // 关闭弹窗时，清空地址数据
  newAddress.value = {
    mobile: '',
    receiver: '',
    provinceCode: '',
    cityCode: '',
    countyCode: '',
    addressDetail: '',
    isDefault: 0 as 0 | 1,
  }
  isDefault.value = false
  result.value = ''
  emit('update:show', false)
}
const showArea = ref(false)
const result = ref('')
const newAddress = ref({
  mobile: '',
  receiver: '',
  provinceCode: '',
  cityCode: '',
  countyCode: '',
  addressDetail: '',
  isDefault: 0 as 0 | 1,
})

// 确认选择地区
const onConfirm = (val: { name: string; code: string }[]) => {
  // console.log(val) // val 是数组，
  result.value = val
    .filter((item) => !!item)
    .map((item) => item.name)
    .join(' ')
  newAddress.value.provinceCode = val[0].code
  newAddress.value.cityCode = val[1].code
  newAddress.value.countyCode = val[2].code
  showArea.value = false
}
const isDefault = ref(false) // 是否默认地址

// 保存地址
const saveAddress = async () => {
  newAddress.value.isDefault = isDefault.value ? 1 : 0
  // 判断是新增地址还是修改地址
  // if (props.id) {
  // }
  if (
    !newAddress.value.receiver ||
    !newAddress.value.mobile ||
    !newAddress.value.addressDetail ||
    !newAddress.value.provinceCode ||
    !newAddress.value.cityCode ||
    !newAddress.value.countyCode
  ) {
    return Toast.fail('请填写完整信息!')
  }
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(newAddress.value.mobile)) {
    return Toast.fail('请输入正确的手机号！')
  }
  try {
    if (props.id) {
      // 编辑地址
      await updateAddressService(
        {
          ...newAddress.value,
        },
        props.id,
      )
      Toast.success('修改地址成功')
    } else {
      await addAddressService(newAddress.value)
      Toast.success('新增地址成功')
    }
    onClose()
    // 刷新地址列表
    emit('refresh')
  } catch (error) {
    console.log(error)
  }
}
const getAddressDetail = async (id: string) => {
  const res = await getAddressDetailService(id)
  newAddress.value = {
    mobile: res.mobile,
    receiver: res.receiver,
    provinceCode: res.provinceCode || '',
    cityCode: res.cityCode || '',
    countyCode: res.countyCode || '',
    addressDetail: res.addressDetail,
    isDefault: res.isDefault as 0 | 1,
  }
  isDefault.value = newAddress.value.isDefault === 1
  result.value = res.province + res.city + (res.county || '')
}
// 回显地址
watch(
  () => props.id,
  (newVal) => {
    // 只有当id变化时，才会进入这里
    if (newVal) {
      // id存在，为编辑地址，调用接口获取地址详情
      getAddressDetail(newVal)
    }
  },
)

// 删除地址
const deleteAddress = async () => {
  try {
    await Dialog.confirm({
      title: '温馨提示',
      message: '确定删除该地址吗？',
    })
    await deleteAddressService(props.id!)
    Toast.success('删除地址成功')
    onClose()
    // 刷新地址列表
    emit('refresh')
  } catch (error) {
    console.log(error)
  }
}
</script>

<template>
  <div>
    <van-popup :show="props.show" position="right" class="add-popup">
      <cp-nav-bar
        :title="id ? '编辑地址' : '新增地址'"
        :back="onClose"
        right-text="保存"
        @click-right="saveAddress"
      ></cp-nav-bar>
      <van-cell-group>
        <van-field
          v-model="newAddress.receiver"
          label="收货人"
          placeholder="请输入收货人"
        ></van-field>
        <van-field
          v-model="newAddress.mobile"
          label="联系方式"
          placeholder="请输入联系方式"
        ></van-field>
        <div>
          <van-field
            v-model="result"
            is-link
            readonly
            name="area"
            label="地区选择"
            placeholder="点击选择省市区"
            @click="showArea = true"
          />
          <!-- 地区选择弹层 -->
          <van-popup v-model:show="showArea" position="bottom">
            <van-area :area-list="areaList" @confirm="onConfirm" @cancel="showArea = false" />
          </van-popup>
        </div>
        <van-field
          v-model="newAddress.addressDetail"
          label="详细地址"
          placeholder="请输入详细地址"
        ></van-field>
        <van-field label="是否默认地址">
          <template #input>
            <van-checkbox v-model="isDefault"></van-checkbox>
          </template>
        </van-field>
      </van-cell-group>
      <van-action-bar v-if="id">
        <van-action-bar-button
          type="danger"
          text="删除"
          @click="deleteAddress"
        ></van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
:deep(.van-popup.add-popup) {
  height: 100vh;
  width: 100%;
  padding-top: 46px;
  box-sizing: border-box;
}
</style>
